/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var Slide = new Class({
    
    Implements: [Options,Events],
    
    options: {
        id  : '',
        url : '',
        html: ''
    },
    
    zones   : [],
    hasSibling   : false,    
    widgets      : {},
    actions      : {},
    
    initialize: function(options){
        this.setOptions(options);
    },
    
    getId: function(){
        return this.options.id;
    },
    
    addFrame: function(htmlId, dataFrame){  
        this.zones[this.zones.length] = {frame : dataFrame, id : htmlId};
    },
    
    load: function(el){
        if(this.options.html.length > 0){
            (function(){
                el.set('html', this.options.html); 
                this.startWidgets();
                this.fireEvent('contentLoaded',[this]);
            }).delay(50,this);
        }else{
            new Request.HTML({
                url: this.options.url,
                update: el,
                onSuccess : function(responseTree, responseElements, responseHTML, responseJavaScript){ 
                    //el.set('html', responseHTML);
                    this.options.html = responseHTML;
                    this.startWidgets();
                    this.fireEvent('contentLoaded',[this]);                   
                }.bind(this)
            }).get({'ajax' : true});
        }         
    },
    
    startWidgets: function(){   
        Object.each(this.widgets, function(widget, key){
            widget.start();
        });
    },
    
    stopWidgets: function(){   
        Object.each(this.widgets, function(widget, key){
            widget.stop();
        });
    },
    
    runActions: function(){   
        Object.each(this.actions, function(run_action, key){
            run_action();
        });
    },
    
    render: function(el){
        this.runActions();
        Array.each(this.zones, function(zone, key){  
            zone.frame.removeEvents();
            zone.frame.addEvent('timelineEnd', function(dataFrame){
                this.fireEvent('checkDescriptor');
                if(dataFrame.isMaster() && this.hasSibling){                                     
                    this.fireEvent('timelineEnd',[this]);
                    this.stopWidgets();
                }else{
                    dataFrame.startLoop();
                }               
            }.bind(this));
            zone.frame.prepareLoop($(zone.id));
            zone.frame.startLoop();
        }.bind(this));
    },
    
    finalize: function(){
        Array.each(this.zones, function(zone, key){
            zone.frame.stopLoop();
        });
    },
    
    setHasSibling: function(value){
        this.hasSibling = value;
    },
    
    registerWidget: function(key, widget){
        this.widgets[key] = widget;
    },
    
    registerAction: function(key, action){
        this.actions[key] = action;
    }
});


